<script setup>
import OImage from "../setting/Images.vue";
import { newRandomUid } from "@/utils";

const props = defineProps({
  config: {
    type: Object,
    required: true,
  },
  name: {
    type: String,
    default: "",
  },
  disabled: {
    type: Boolean,
    default: false,
  },
  groupType: {
    type: String,
    default: "",
  },
  group: {
    type: Array,
    default: () => [],
  },
});

const emits = defineEmits(["update:config", "change"]),
  customPageList = inject("customPageList", []),
  popupList = inject("popupList");

const form = ref({
  $position: { top: 0, left: 0 },
  $size: { width: 79, height: 26 },
  $positionType: "absolute",
  $removeable: true,
  linkType: "none",
  img: "./imagesStatic/activity/button_default.png",
  shareDesc: "",
  shareTitle: "",
  link: "",
});

const formRef = ref();

const typeList = [
  { label: "无", key: "none" },
  { label: "功能", key: "system" },
  { label: "弹窗", key: "popup" },
  { label: "链接", key: "link" },
  { label: "自定义页面", key: "customPage" },
];

const pageFuncList = ref([
    { label: "我的订单（我的奖品）", key: "order" },
    { label: "分享（仅分享）", key: "share" },
    { label: "分享裂变（分享奖励）", key: "invite", show: false },
    { label: "邀请记录", key: "inviteRecord" },
    { label: "客服", key: "kefu" },
    { label: "答题", key: "answer", show: false },
    { label: "排行榜", key: "rank", show: false },
  ]),
  popupFuncList = ref([
    { label: "关闭弹窗", key: "closePopup" },
    { label: "我的订单（我的奖品）", key: "order" },
  ]);

const shareTypeList = [
  { label: "海报", key: "poster" },
  { label: "微信网页分享", key: "wechat" },
];

const rules = {
  linkType: [{ required: true, message: "请选择跳转类型", trigger: "change" }],
  type: [{ required: true, message: "请选择按钮功能", trigger: "change" }],
  link: [{ required: true, message: "请填写跳转链接", trigger: "blur" }],
  popupUid: [{ required: true, message: "请选择关联弹窗", trigger: "change" }],
  answerUid: [{ required: true, message: "请选择答题区域", trigger: "change" }],
  shareType: [{ required: true, message: "请选择分享类型", trigger: "change" }],
  shareTitle: [{ required: true, message: "请填写分享标题", trigger: "blur" }],
  shareDesc: [{ required: true, message: "请填写分享描述", trigger: "blur" }],
  shareIcon: [{ required: true, message: "请上传分享图标", trigger: "change" }],
  sharePosterUid: [
    { required: true, message: "请上绑定分享海报", trigger: "change" },
  ],
  customPageUid: [
    { required: true, message: "请选择跳转页面", trigger: "change" },
  ],
};

const positionList = [
  { label: "默认", key: "relative" },
  { label: "浮动", key: "absolute" },
];

const detail = computed({
  get: () => {
    return Object.assign({}, form.value, props.config);
  },
  set: (val) => {
    emits("update:config", val);
    emits("change", val);
  },
});

const sharePopup = computed(() => {
  return popupList.value.filter(
    (item) => item.pageConfig.type === "sharePoster"
  );
});

const commonPopup = computed(() => {
  return popupList.value.filter(
    (item) =>
      item.pageConfig.type === "none" ||
      item.pageConfig.type === "richText" ||
      item.type === "CustomPopup"
  );
});

const _commonPopup = computed(() => {
  return (props.group || []).filter(
    (item) =>
      item.pageConfig.type === "none" ||
      item.pageConfig.type === "richText" ||
      item.type === "CustomPopup"
  );
});

const answerPopup = computed(() => {
  return popupList.value.filter((item) => item.type === "Answer");
});

const privateType = computed(() => {
  if (detail.value.linkType === "system") {
    let func = funcList.value.find((item) => item.key === detail.value.type);
    if (func && func.show === false) {
      return true;
    }
  }
  return false;
});

const funcList = computed(() => {
  if (props.groupType === "CustomPopup") return popupFuncList.value;
  return pageFuncList.value;
});

const onChangeFunc = () => {
  // 分享海报
  if (
    detail.value.linkType === "system" &&
    (detail.value.type === "invite" || detail.value.type === "share") &&
    detail.value.shareType === "poster"
  ) {
    if (!detail.value.$pageFlag) {
      detail.value.$pageFlag = `shareFlag-${newRandomUid()}`;
    }
    if (sharePopup.value.length > 0)
      detail.value.sharePosterUid = sharePopup.value[0].uid;
    else {
      let uid = newRandomUid();
      detail.value.sharePosterUid = uid;
      emits("change", detail.value, {
        uid: uid,
        name: "分享海报",
        type: "Popup",
        pageConfig: {
          type: "sharePoster",
        },
      });
    }
  }
  onChange();
};

const changePositionType = () => {
  detail.value.$position = { left: 0, top: 0 };
  onChange();
};

const onChange = (val) => {
  detail.value = detail.value;
};

// 表单校验
const check = () => {
  return new Promise((resolve, reject) => {
    formRef.value.validate(async (valid, invalidFields) => {
      if (valid) {
        // 弹窗按钮是否关联弹窗
        if (
          detail.value.linkType === "popup" &&
          !commonPopup.value.find((item) => item.uid === detail.value.popupUid)
        ) {
          detail.value.popupUid = "";
          reject(`${props.name}未关联弹窗`);
        }
        // 分享按钮是否关联海报
        if (
          detail.value.linkType === "system" &&
          (detail.value.type === "share" || detail.value.type === "invite") &&
          detail.value.shareType === "poster" &&
          !sharePopup.value.find(
            (item) => item.uid === detail.value.sharePosterUid
          )
        ) {
          detail.value.sharePosterUid = "";
          reject(`${props.name}未关联分享海报`);
        }
        resolve();
      } else
        reject(
          `${props.name}校验未通过，${
            invalidFields[Object.keys(invalidFields)[0]][0].message
          }`
        );
    });
  });
};

const hrefVisible = ref(false);
const linkModel = ref({
  urlType: "manual",
  url: "",
});
const addHref = () => {
  linkModel.value.url = detail.value.link;
  hrefVisible.value = true;
}
const confirmHref = (link) => {
  linkModel.value = link
  detail.value.urlType=link.linkType||''
  detail.value.link = link.url
  onChange();
}

onMounted(() => {
  nextTick(() => {
    onChange();
  });
});

defineExpose({ check });
</script>
<template>
  <div>
    <el-form
      ref="formRef"
      :model="detail"
      :rules="rules"
      :disabled="disabled"
      label-width="auto"
    >
      <el-form-item label="位置类型">
        <el-radio-group
          v-model="detail.$positionType"
          @change="changePositionType"
        >
          <el-radio v-for="item in positionList" :label="item.key">{{
            item.label
          }}</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="跳转类型:" prop="linkType">
        <el-radio-group
          v-model="detail.linkType"
          :disabled="privateType"
          @change="onChange"
        >
          <el-radio v-for="item in typeList" :label="item.key">{{
            item.label
          }}</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item
        v-if="detail.linkType === 'system'"
        label="按钮功能:"
        prop="type"
      >
        <el-select
          v-model="detail.type"
          placeholder="请选择"
          style="width: 200px"
          :disabled="privateType"
          @change="onChangeFunc"
        >
          <template v-for="(item, key) in funcList" :key="key">
            <el-option
              v-if="(!privateType && item.show !== false) || privateType"
              :label="item.label"
              :value="item.key"
            />
          </template>
        </el-select>
      </el-form-item>
      <el-form-item
        v-else-if="detail.linkType === 'link'"
        label="跳转链接:"
        prop="link"
      >
        <div style="width: 340px;overflow: hidden;text-overflow: ellipsis;word-break: keep-all;white-space: nowrap" v-if="detail.link">{{detail.link}}</div>
        <div>
          <el-button @click="addHref">添加链接</el-button>
        </div>
<!--        <el-input v-model="detail.link" @input="onChange"></el-input>-->
      </el-form-item>
      <el-form-item
        v-else-if="detail.linkType === 'popup'"
        label="关联弹窗:"
        prop="popupUid"
      >
        <el-select
          v-model="detail.popupUid"
          placeholder="请选择"
          style="width: 200px"
          @change="onChange"
        >
          <el-option-group v-if="commonPopup.length > 0" label="内部弹窗">
            <el-option
              v-for="(item, key) in commonPopup"
              :label="item.name"
              :value="item.uid"
            />
          </el-option-group>
          <el-option-group v-if="_commonPopup.length > 0" label="外部弹窗">
            <el-option
              v-for="(item, key) in _commonPopup"
              :label="item.name"
              :value="item.uid"
            />
          </el-option-group>
        </el-select>
      </el-form-item>
      <el-form-item
        v-if="detail.linkType === 'system' && detail.type === 'answer'"
        label="答题区域:"
        prop="answerUid"
      >
        <el-select
          v-model="detail.answerUid"
          placeholder="请选择"
          style="width: 200px"
          @change="onChange"
        >
          <el-option
            v-for="(item, key) in answerPopup"
            :label="item.name"
            :value="item.uid"
          />
        </el-select>
      </el-form-item>
      <template
        v-if="
          detail.linkType === 'system' &&
          (detail.type === 'share' || detail.type === 'invite')
        "
      >
        <el-form-item label="分享类型:" prop="shareType">
          <el-radio-group v-model="detail.shareType" @change="onChangeFunc">
            <el-radio v-for="item in shareTypeList" :label="item.key">{{
              item.label
            }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <template v-if="detail.shareType === 'wechat'">
          <el-form-item label="分享标题:" prop="shareTitle">
            <el-input
              v-model="detail.shareTitle"
              style="width: 400px"
              @input="onChange"
            ></el-input>
          </el-form-item>
          <el-form-item label="分享描述:" prop="shareDesc">
            <el-input
              v-model="detail.shareDesc"
              style="width: 400px"
              @input="onChange"
            ></el-input>
          </el-form-item>
          <el-form-item label-width="0" prop="shareIcon">
            <OImage
              v-model="detail.shareIcon"
              tips="建议尺寸：1:1（如50px*50px）"
              name="分享图标"
              @change="onChange"
            />
          </el-form-item>
        </template>
        <template v-else-if="detail.shareType === 'poster'">
          <el-form-item label="分享海报:" prop="sharePosterUid">
            <el-select
              v-model="detail.sharePosterUid"
              placeholder="请选择"
              style="width: 200px"
              @change="onChange"
            >
              <el-option
                v-for="(item, key) in sharePopup"
                :label="item.name"
                :value="item.uid"
              />
            </el-select>
          </el-form-item>
        </template>
      </template>
      <el-form-item
        v-if="detail.linkType === 'customPage'"
        label="跳转页面"
        prop="customPageUid"
      >
        <el-select
          v-model="detail.customPageUid"
          placeholder="请选择"
          style="width: 200px"
          @change="onChange"
        >
          <el-option
            v-for="(item, key) in customPageList"
            :label="item.pageName"
            :value="item.uid"
          />
        </el-select>
      </el-form-item>
      <OImage
        v-model="detail.img"
        v-model:size="detail.$size"
        name="按钮图片"
        @change="onChange"
      />
    </el-form>

    <href-selector
        v-model:show="hrefVisible"
        :model-value="linkModel"
        @confirm="confirmHref"
        :disable-tab="['mallProduct', 'mallPage']"
    ></href-selector>
  </div>
</template>
